import { useQueryState } from "nuqs";
import {
  createContext,
  useContext,
  ReactNode,
  useCallback,
  useState,
  Dispatch,
  SetStateAction,
} from "react";
import { useStreamContext } from "./Stream"; // 添加这个import
import { v4 as uuidv4 } from "uuid";

// 自定义Thread类型
interface CustomThread {
  thread_id: string;
  created_at: string;
  updated_at: string;
  metadata?: Record<string, any>;
  last_message: string;
  messages?: Array<{
    // 更新：直接使用messages字段
    role: string;
    content: string;
    [key: string]: any;
  }>;
  values?: {
    messages?: Array<{
      content: string;
      [key: string]: any;
    }>;
  };
}
interface ThreadContextType {
  getThreads: () => Promise<CustomThread[]>;
  threads: CustomThread[];
  setThreads: Dispatch<SetStateAction<CustomThread[]>>;
  threadsLoading: boolean;
  setThreadsLoading: Dispatch<SetStateAction<boolean>>;
}

const ThreadContext = createContext<ThreadContextType | undefined>(undefined);

// 简化的线程搜索函数
function getThreadSearchParams(assistantId: string) {
  return {
    assistant_id: assistantId,
    limit: 100,
  };
}

// 创建默认线程的辅助函数
const createDefaultThread = (userId: string): CustomThread => {
  // 生成一个新的唯一ID作为conversation_id
  const conversationId = uuidv4();
  
  // 按照后端要求的格式组合thread_id
  const threadId = `${userId}@@${conversationId}`;

  return {
    thread_id: threadId, // 使用userId和conversationId组合
    created_at: new Date().toISOString(),
    updated_at: new Date().toISOString(),
    metadata: {
      gid: userId, // 使用userId填充gid
      userId: userId,
      conversationId: conversationId // 保留conversationId在metadata中以便后续使用
    },
    last_message: "欢迎使用Agent Chat！",
    messages: [],
    values: {
      messages: [
        {
          content: "欢迎使用Agent Chat！",
        },
      ],
    },
  };
};

export function ThreadProvider({ children }: { children: ReactNode }) {
  const [apiUrl] = useQueryState("apiUrl", {
    defaultValue: process.env.NEXT_PUBLIC_API_URL || "http://localhost:8013",
  });
  const [assistantId] = useQueryState("assistantId", {
    defaultValue: process.env.NEXT_PUBLIC_ASSISTANT_ID || "agent",
  });
  const [threads, setThreads] = useState<CustomThread[]>([]);
  const [threadsLoading, setThreadsLoading] = useState(false);

  // 从StreamContext获取userId
  const stream = useStreamContext();
  const userId = stream.userId;

  const getThreads = useCallback(async (): Promise<CustomThread[]> => {
    if (!apiUrl || !assistantId) {
      console.warn("API URL or Assistant ID not configured");
      return userId ? [createDefaultThread(userId)] : [];
    }

    try {
      // 构建查询参数，包含userId
      const params = new URLSearchParams();
      if (userId) {
        params.append("userId", userId);
      }
      params.append("limit", "100");
      params.append("offset", "0");

      const url = `${apiUrl}/threads?${params.toString()}`;
      console.log("Fetching threads from:", url);

      const response = await fetch(url, {
        method: "GET",
        headers: {
          "Content-Type": "application/json",
        },
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const data = await response.json();
      console.log("API Response:", data);

      // 处理后端返回的数据格式
      const threads = data.threads || [];

      // 如果threads为空且有userId，创建一个默认的thread对象
      if (threads.length === 0 && userId) {
        console.log(
          "Threads array is empty, creating default thread with userId@@conversationId format",
        );
        return [createDefaultThread(userId)];
      }

      return threads.map((thread: any) => ({
        thread_id: thread.thread_id,
        created_at: thread.created_at,
        updated_at: thread.updated_at,
        metadata: thread.metadata || {},
        messages: thread.messages || [],
        last_message: thread.last_message,
        values:
          thread.messages && thread.messages.length > 0
            ? { messages: thread.messages }
            : thread.last_message
              ? { messages: [{ content: thread.last_message }] }
              : undefined,
      }));
    } catch (error) {
      console.error("Error fetching threads:", error);
      // 在错误情况下，如果有userId，也创建一个默认的thread对象
      return userId ? [createDefaultThread(userId)] : [];
    }
  }, [apiUrl, assistantId, userId]);

  const value = {
    getThreads,
    threads,
    setThreads,
    threadsLoading,
    setThreadsLoading,
  };

  return (
    <ThreadContext.Provider value={value}>{children}</ThreadContext.Provider>
  );
}

export function useThreads() {
  const context = useContext(ThreadContext);
  if (context === undefined) {
    throw new Error("useThreads must be used within a ThreadProvider");
  }
  return context;
}
